<!--
  * 供应商表单弹窗
  *
  * @Author:    1024创新实验室
  * @Date:      2024-07-19 20:30:00
  * @Wechat:    zhuoda1024
  * @Email:     lab1024@163.com
  * @Copyright  1024创新实验室 （ https://1024lab.net ），Since 2012
-->
<template>
  <a-modal 
    :title="modalTitle" 
    :width="800" 
    :open="visible" 
    :body-style="{ paddingBottom: '80px' }" 
    @cancel="onClose"
    @ok="onSubmit"
    :confirmLoading="confirmLoading"
    :maskClosable="false"
  >
    <a-form ref="formRef" :model="form" :rules="rules" :label-col="{ span: 6 }" :wrapper-col="{ span: 18 }">
      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item label="供应商编码" name="supplierCode">
            <a-input v-model:value="form.supplierCode" placeholder="请输入供应商编码" :disabled="readonly" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="供应商名称" name="supplierName">
            <a-input v-model:value="form.supplierName" placeholder="请输入供应商名称" :disabled="readonly" />
          </a-form-item>
        </a-col>
      </a-row>

      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item label="供应商类型" name="supplierType">
            <SmartEnumSelect enum-name="SUPPLIER_TYPE_ENUM" v-model:value="form.supplierType" :disabled="readonly" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="状态" name="status">
            <SmartEnumSelect enum-name="SUPPLIER_STATUS_ENUM" v-model:value="form.status" :disabled="readonly" />
          </a-form-item>
        </a-col>
      </a-row>

      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item label="联系人" name="contactPerson">
            <a-input v-model:value="form.contactPerson" placeholder="请输入联系人" :disabled="readonly" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="联系电话" name="contactPhone">
            <a-input v-model:value="form.contactPhone" placeholder="请输入联系电话" :disabled="readonly" />
          </a-form-item>
        </a-col>
      </a-row>

      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item label="联系邮箱" name="contactEmail">
            <a-input v-model:value="form.contactEmail" placeholder="请输入联系邮箱" :disabled="readonly" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="信用等级" name="creditRating">
            <SmartEnumSelect enum-name="SUPPLIER_CREDIT_RATING_ENUM" v-model:value="form.creditRating" :disabled="readonly" />
          </a-form-item>
        </a-col>
      </a-row>

      <a-row :gutter="16">
        <a-col :span="24">
          <a-form-item label="地址" name="address" :label-col="{ span: 3 }" :wrapper-col="{ span: 21 }">
            <a-input v-model:value="form.address" placeholder="请输入地址" :disabled="readonly" />
          </a-form-item>
        </a-col>
      </a-row>

      <a-row :gutter="16" v-if="form.supplierType === 2">
        <a-col :span="12">
          <a-form-item label="营业执照号" name="businessLicense">
            <a-input v-model:value="form.businessLicense" placeholder="请输入营业执照号" :disabled="readonly" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="纳税人识别号" name="taxNumber">
            <a-input v-model:value="form.taxNumber" placeholder="请输入纳税人识别号" :disabled="readonly" />
          </a-form-item>
        </a-col>
      </a-row>

      <a-row :gutter="16">
        <a-col :span="12">
          <a-form-item label="银行账号" name="bankAccount">
            <a-input v-model:value="form.bankAccount" placeholder="请输入银行账号" :disabled="readonly" />
          </a-form-item>
        </a-col>
        <a-col :span="12">
          <a-form-item label="开户银行" name="bankName">
            <a-input v-model:value="form.bankName" placeholder="请输入开户银行" :disabled="readonly" />
          </a-form-item>
        </a-col>
      </a-row>

      <a-row :gutter="16">
        <a-col :span="24">
          <a-form-item label="备注" name="remark" :label-col="{ span: 3 }" :wrapper-col="{ span: 21 }">
            <a-textarea 
              v-model:value="form.remark" 
              placeholder="请输入备注" 
              :rows="3"
              :maxlength="500"
              :disabled="readonly"
            />
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>

    <template #footer v-if="!readonly">
      <a-button @click="onClose">取消</a-button>
      <a-button type="primary" :loading="confirmLoading" @click="onSubmit">提交</a-button>
    </template>
    <template #footer v-else>
      <a-button @click="onClose">关闭</a-button>
    </template>
  </a-modal>
</template>

<script setup>
  import { ref, nextTick, reactive, computed } from 'vue';
  import { message } from 'ant-design-vue';
  import { SmartLoading } from '/@/components/framework/smart-loading';
  import _ from 'lodash';
  import { supplierApi } from '/@/api/business/purchase/supplier/supplier-api';
  import { smartSentry } from '/@/lib/smart-sentry';
  import SmartEnumSelect from '/@/components/framework/smart-enum-select/index.vue';
  import { SUPPLIER_TYPE_ENUM, SUPPLIER_STATUS_ENUM } from '/@/constants/business/purchase/supplier-const';

  // emit
  const emit = defineEmits(['reloadList']);

  // 组件ref
  const formRef = ref();

  const formDefault = {
    supplierId: undefined,
    supplierCode: '',
    supplierName: '',
    supplierType: SUPPLIER_TYPE_ENUM.ENTERPRISE.value,
    contactPerson: '',
    contactPhone: '',
    contactEmail: '',
    address: '',
    businessLicense: '',
    taxNumber: '',
    bankAccount: '',
    bankName: '',
    creditRating: 'C',
    status: SUPPLIER_STATUS_ENUM.ENABLED.value,
    remark: '',
  };

  let form = reactive({ ...formDefault });

  // 表单验证规则
  const rules = {
    supplierCode: [
      { required: true, message: '供应商编码不能为空' },
      { max: 50, message: '供应商编码最多50字符' },
    ],
    supplierName: [
      { required: true, message: '供应商名称不能为空' },
      { max: 100, message: '供应商名称最多100字符' },
    ],
    supplierType: [{ required: true, message: '请选择供应商类型' }],
    status: [{ required: true, message: '请选择状态' }],
    contactPhone: [
      { pattern: /^[0-9-]{0,20}$/, message: '联系电话格式不正确' },
    ],
    contactEmail: [
      { type: 'email', message: '邮箱格式不正确' },
      { max: 100, message: '邮箱最多100字符' },
    ],
    contactPerson: [{ max: 50, message: '联系人最多50字符' }],
    address: [{ max: 200, message: '地址最多200字符' }],
    businessLicense: [{ max: 100, message: '营业执照号最多100字符' }],
    taxNumber: [{ max: 50, message: '纳税人识别号最多50字符' }],
    bankAccount: [{ max: 50, message: '银行账号最多50字符' }],
    bankName: [{ max: 100, message: '开户银行最多100字符' }],
    remark: [{ max: 500, message: '备注最多500字符' }],
  };

  // 是否展示弹窗
  const visible = ref(false);
  const confirmLoading = ref(false);
  const readonly = ref(false);

  // 弹窗标题
  const modalTitle = computed(() => {
    if (readonly.value) {
      return '查看供应商';
    }
    return form.supplierId ? '编辑供应商' : '新增供应商';
  });

  function showModal(rowData, isReadonly = false) {
    Object.assign(form, formDefault);
    readonly.value = isReadonly;
    
    if (rowData && !_.isEmpty(rowData)) {
      Object.assign(form, rowData);
    }
    
    visible.value = true;
    nextTick(() => {
      formRef.value?.clearValidate();
    });
  }

  function onClose() {
    Object.assign(form, formDefault);
    visible.value = false;
    readonly.value = false;
    confirmLoading.value = false;
  }

  function onSubmit() {
    if (readonly.value) {
      onClose();
      return;
    }

    formRef.value
      .validate()
      .then(async () => {
        confirmLoading.value = true;
        try {
          if (form.supplierId) {
            await supplierApi.update(form);
          } else {
            await supplierApi.add(form);
          }
          message.success(`${form.supplierId ? '修改' : '添加'}成功`);
          onClose();
          emit('reloadList');
        } catch (error) {
          smartSentry.captureError(error);
        } finally {
          confirmLoading.value = false;
        }
      })
      .catch((error) => {
        console.log('error', error);
        message.error('参数验证错误，请仔细填写表单数据!');
      });
  }

  defineExpose({
    showModal,
  });
</script>

<style scoped>
  .ant-form-item {
    margin-bottom: 16px;
  }
</style>